package top.qitun.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import top.qitun.bizz.client.client.entity.ClientBO;
import top.qitun.bizz.client.client.service.ClientService;
import top.qitun.exception.RestStatusException;
import top.qitun.modal.request.ClientCreateRequest;
import top.qitun.model.response.ObjectDataResponse;
import top.qitun.model.security.AuthenticationDTO;
import top.qitun.util.OrikaMapper;

/**
 * 店铺创建类
 * 
 * @author Cloudwei
 *
 */
@RestController
@RequestMapping(value = "/v1")
public class ClientController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ClientService clientService;

	@ApiOperation(value = "点餐用户注册", notes = "点餐用户操作")
	@RequestMapping(value = "/client", method = RequestMethod.POST)
	public ObjectDataResponse<ClientBO> register(@Valid @RequestBody ClientCreateRequest request) {
		String desc = "用户注册";
		try {
			final ClientBO dbUser = clientService.queryBywxOpenId(request.getWxopenid());
			if (dbUser != null) {
				logger.warn("用户已注册!");
				return new ObjectDataResponse<ClientBO>(1, desc + "失败,用户已存在!");
			}

			ClientBO transientUser = OrikaMapper.map(request, ClientBO.class);
			clientService.add(transientUser);
			// RegisterResponse returnObject = OrikaMapper.map(transientUser,
			// RegisterResponse.class);
			return new ObjectDataResponse<ClientBO>(0, desc + "用户成功!", transientUser);
		} catch (Exception e) {
			logger.error("用户注册失败", e);
			return new ObjectDataResponse<ClientBO>(-1, "系统错误!" + e.getMessage());
		}
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ObjectDataResponse<ClientBO> authenticate(@RequestBody AuthenticationDTO authenticationDTO) {
		String desc = "验证用户";
		try {
			// Authenticate the user
			ClientBO userDTO = clientService.queryBywxOpenId(authenticationDTO.getWxopenid());
			return new ObjectDataResponse<ClientBO>(0, "授权成功!", userDTO);
		} catch (RestStatusException e) {
			return new ObjectDataResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			return new ObjectDataResponse<>(-1, desc + "失败,请联系客服!");
		}
	}

}
